<?php
namespace App\Models;

use App\Models\Product;
use App\Models\ProductStock;
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Str;
use Auth;
use Storage;

//class ProductsImport implements ToModel, WithHeadingRow, WithValidation
class ProductsImport implements ToCollection, WithHeadingRow, WithValidation, ToModel
{
    private $rows = 0;
    
    public function collection(Collection $rows) {
        $canImport = true;
        if (addon_is_activated('seller_subscription')){
            if(Auth::user()->user_type == 'seller' && Auth::user()->seller->seller_package && (count($rows) + Auth::user()->seller->user->products()->count()) > Auth::user()->seller->seller_package->product_upload_limit) {
                $canImport = false;
                flash(translate('Upload limit has been reached. Please upgrade your package.'))->warning();
            }
        }
 
        if($canImport) {
            foreach ($rows as $row) {
				$approved = 1;
				if(Auth::user()->user_type == 'seller' && get_setting('product_approve_by_admin') == 1) {
					$approved = 0;
				}
				
                $productId = Product::create([
                            'name' => $row['name'],
                            'added_by' => Auth::user()->user_type == 'seller' ? 'seller' : 'admin',
                            'user_id' => Auth::user()->user_type == 'seller' ? Auth::user()->id : User::where('user_type', 'admin')->first()->id,
                            'approved' => $approved,
							'category_id' => $row['category_id'],
                            'brand_id' => $row['brand_id'],
                            'video_provider' => $row['video_provider'],
                            'video_link' => $row['video_link'],
                            'qty' => $row['qty'],
                            'unit_price' => $row['unit_price'],
                            'purchase_price' => $row['purchase_price'] == null ? $row['unit_price'] : $row['purchase_price'],
                            'unit' => $row['unit'],
                            'meta_title' => $row['meta_title'],
                            'meta_description' => $row['meta_description'],
                            'description' => $row['description'],
                            'colors' => json_encode(array()),
                            'choice_options' => json_encode(array()),
                            'variations' => json_encode(array()),
                            'slug' => preg_replace('/[^A-Za-z0-9\-]/', '', str_replace(' ', '-', strtolower($row['slug']))) . '-' . Str::random(5),
                            'thumbnail_img' => $this->downloadThumbnail2($row['thumbnail_img'],'thumbnail'),
                             'photos' => $this->downloadThumbnail2($row['photos'],'photos'),
                ]);
                
             
                ProductStock::create([
                    'product_id' => $productId->id,
                    'qty' => $row['qty'],
                    'price' => $row['unit_price'],
                    'variant' => '',
                ]);
            }
            
            flash(translate('Products imported successfully'))->success();
        }
        
        
    }
    
    public function model(array $row)
    {
        ++$this->rows;
    }
    
    public function getRowCount(): int
    {
        return $this->rows;
    }

    public function rules(): array
    {
        return [
             // Can also use callback validation rules
             'unit_price' => function($attribute, $value, $onFailure) {
                  if (!is_numeric($value)) {
                       $onFailure('Unit price is not numeric');
                  }
              }
        ];
    }

    public function downloadThumbnail3($url)
    {
        try {
            $extension = pathinfo($url, PATHINFO_EXTENSION);
            $filename = 'uploads/all/'.Str::random(5).'.'.$extension;
            $fullpath = 'public/'.$filename;
            $file = file_get_contents($url);
            file_put_contents($fullpath, $file);

            $upload = new Upload;
            $upload->extension = strtolower($extension);

            $upload->file_original_name = $filename;
            $upload->file_name = $filename;
            $upload->user_id = Auth::user()->id;
            $upload->type = "image";
            $upload->file_size = filesize(base_path($fullpath));
            $upload->save();

            if(env('FILESYSTEM_DRIVER') == 's3'){
                $s3 = Storage::disk('s3');
                $s3->put($filename, file_get_contents(base_path($fullpath)));
                unlink(base_path($fullpath));
            }

            return $upload->id;
        } catch (\Exception $e) {
            //dd($e);
        }
        return null;
    }
    
    public function downloadThumbnail($url,$type= 'thumbnail')
    {
        if( $type == 'thumbnail')
        {
            try 
            {
                $extension = pathinfo($url, PATHINFO_EXTENSION);
                //if( strpos( $url ,'https') !== false  )
                 if( 0 )
                {
                    $filename = $url;
                    $filesize = 888;
                }
                else 
                {
                        $filename = 'uploads/all/'.Str::random(5).'.'.$extension;
                        $fullpath = 'public/'.$filename;
                        $file = file_get_contents($url);
                        file_put_contents($fullpath, $file);
                        $filesize =  filesize(base_path($fullpath));;
                }
              
    
                $upload = new Upload;
                $upload->extension = strtolower($extension);
    
                $upload->file_original_name = $filename;
                $upload->file_name = $filename;
                $upload->user_id = 1;
                $upload->type = "image";
                $upload->file_size = $filesize;
                $upload->save();
    
              
                return $upload->id;
            } catch (\Exception $e) {
                //dd($e);
            }
        }
        if( $type == 'photos')
        {
            $urls = explode("\n", $url );
          
            $ps = '';
            foreach( $urls as $url )
            {
                if( empty($url)) continue;
                try 
                {
                        $extension = pathinfo($url, PATHINFO_EXTENSION);
                        //if( strpos( $url ,'http') !== false  )
                        
                          if( 0 )
                        {
                            $filename = $url;
                            $filesize = 888;
                        }
                        else 
                        {
                                $filename = 'uploads/all/'.Str::random(5).'.'.$extension;
                                $fullpath = 'public/'.$filename;
                                $file = file_get_contents($url);
                                file_put_contents($fullpath, $file);
                                $filesize =  filesize(base_path($fullpath));;
                        }
                      
            
                        $upload = new Upload;
                        $upload->extension = strtolower($extension);
            
                        $upload->file_original_name = $filename;
                        $upload->file_name = $filename;
                        $upload->user_id = 1;
                        $upload->type = "image";
                        $upload->file_size = $filesize;
                        $upload->save();
            
                        if(env('FILESYSTEM_DRIVER') == 's3')
                        {
                            $s3 = Storage::disk('s3');
                            $s3->put($filename, file_get_contents(base_path($fullpath)));
                            unlink(base_path($fullpath));
                        }
            
                        $ps .= $upload->id;
                        $ps .= ',';
                    } catch (\Exception $e) {
                        //dd($e);
                    }
            }
          
            $ps = rtrim( $ps, ',');
 
            return $ps;
        }
        return null;
    }
    
 
    
    
    
    
     public function downloadThumbnail22($url){
        try {
            $upload = new Upload;
            $upload->external_link = $url;
            $upload->save();

            return $upload->id;
        } catch (\Exception $e) {
            
        }
        return null;
    }

    public function downloadGalleryImages($urls){
        $data = array();
        foreach(explode(',', str_replace(' ', '', $urls)) as $url){
            if($url!='' && !strstr($url,'.gif')){
                   
                  if(1) {
                      
                       $z  = (explode(',',$url));

                       $urz =  $z[0].'.jpg';
                
                       $data[] = $this->downloadThumbnail($urz);
                      
                  }
              
            }
           
        }
        return implode(',', $data);
    }
    
    
      public function caiji($res) {
           
          //var_dump($this->downloadThumbnail($res['img'])); exit;
 
        $choice_options = array();
        if($res) {
       
                $productId = Product::create([
                            'name' => $res['name'],  //产品库
                            'description' => $res['tt'], //产品库
                            'added_by' =>  'admin', //产品库
                            'user_id' => 9, //产品库
                            'approved' => '', //产品库
							'category_id' => 8, //产品分类
                            'brand_id' => 1,
                            'video_provider' => '',
                            'video_link' =>'',
                            'unit_price' => str_replace('¥','',$res['price']),
                            'purchase_price' => str_replace('¥','',$res['price']),
                            'unit' => '',
                            'meta_title' => $res['name'],
                            'meta_description' => $res['tt'],
                            'colors' => json_encode(array()),
                            'choice_options' => json_encode(array()),
                            'variations' => json_encode(array()),
                            'slug' =>preg_replace('/[^A-Za-z0-9\-]/', '', str_replace(' ', '-', strtolower( $res['name']))).'-'.md5(microtime()),
                            'thumbnail_img' => $this->downloadThumbnail($res['img']),
                            'photos' => $this->downloadGalleryImages($res['imgs']),
                            'published'=>'1', 
                            'choice_options'=>json_encode($choice_options, JSON_UNESCAPED_UNICODE),
                            'cpk'=>1,  //产品库
                            'unit'=>'PC',
                            'discount'=>0,
                            'current_stock'=>10000,
                             
                            
                ]);
                ProductStock::create([
                    'product_id' => $productId->id,
                    'qty' => '',
                    'price' => '',
                    'variant' => '',
                ]);
            }
            
            //flash(translate('Products imported successfully'))->success();
      
        
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
